package com.yunchuang.service;

import com.yunchuang.constants.FileStatusConstants;
import com.yunchuang.pojo.FileInfo;
import com.yunchuang.utils.ProfileUtils;

import java.io.*;
import java.net.Socket;

import static com.yunchuang.constants.FileStatusConstants.FILE_DELETE;

/**
 * 文件上传
 *
 * @author ItJiange
 * @date 2023/10/19
 */
public class FileUploadService {
    public void sendFileMessage(File file, String fileStatus) {
        // 创建 socket 对象
        try (Socket socket = new Socket(ProfileUtils.getHost(), ProfileUtils.getPort())) {
            // 创建文件对象
            String fileName = file.getName();
            // TODO
            byte[] fileMessage = FILE_DELETE.equals(fileStatus) ? null : getFileByte(file.getAbsolutePath());
            FileInfo fileInfo = new FileInfo(fileName, fileStatus, fileMessage);
            // 写入 socket 输出流
            writeFileInfo(socket, fileInfo);
            ProfileUtils.closeStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将文件对象进行序列化
     * @param socket
     * @param fileInfo
     */
    private static void writeFileInfo(Socket socket, FileInfo fileInfo) {
        // 获取 socket 输出流
        try (OutputStream fileOutput = socket.getOutputStream();
             ObjectOutputStream fileInfoOutput = new ObjectOutputStream(fileOutput);) {
            fileInfoOutput.writeObject(fileInfo);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取文件内容
     * @param fileAbsolutePath 完整文件路径
     * @return
     */
    private static byte[] getFileByte(String fileAbsolutePath) {
        try (FileInputStream fis = new FileInputStream(fileAbsolutePath);
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            fis.transferTo(bos);
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return new byte[0];
        }
    }
}
